<?php

namespace app\admin\controller;

use think\Config;
use think\Controller;
use think\Db;
use think\Exception;

//生成数据
class Generate extends Controller
{
    //生成用户
    public function generateUser()
    {
        $i = 100000;
        $data = [];

        while ($i--) {
            $mobile = 13000000000 + $i;
            $data[] = [
                'nickname' => $mobile,
                'mobile' => $mobile,
                'createtime' => time(),
                'updatetime' => time(),
            ];

            if ($i != 100000 && $i % 100 == 0) {
                Db::table('member')->insertAll($data);
                $data = [];
            }
        }

        //剩余信息
        if (!empty($data)) {
            Db::table('member')->insertAll($data);
        }

        echo "生成完了";
    }


    public function generateOrder()
    {
        //临时内存
        ini_set('memory_limit', '-1');

        $i = 500000;
        $data = [];

        $memberArr = [];
        //用户总数
        $memberCount = Db::table('member')->count();

        //产品列表
        $products = Db::table('product')->field('id,title,price,stock')->where('stock', '>', 0)->select();
        $products = array_column($products, null, 'id');
        //产品ids
        $productIds = array_column($products, 'id');

        //产品总数
        $productIdCount = count($productIds) - 1;

        while ($i--) {
            //随机取用户数据
            $member = $this->_randMember($memberArr, $memberCount);

            //下单时间
            $createTime = time() - rand(0, 7 * 86400);
            $payTime = null;

            //订单号
            $orderNo = "wx" . $createTime . date("Ymd", $createTime) . rand(1111, 9999) . str_pad($member['id'], 8, '0', STR_PAD_LEFT);

            //随机数量
            $num = rand(1, 5);

            //随机取产品信息
            $product = $this->_randProduct($products, $productIds, $productIdCount, $num);

            //价格
            $price = bcmul($product['price'], $num, 2);

            //订单状态
            $status = 0;

            //支付类型 && 支付时间
            $payType = rand(0, 1);
            if ($payType == 1) {
                $status = 2; //已完成
                $payTime = $createTime + rand(1, 10);
            }

            $data[] = [
                'order_no' => $orderNo,
                'member_id' => $member['id'],
                'nickname' => $member['nickname'],
                'mobile' => $member['mobile'],
                'address' => '辽宁沈阳市浑南新区五三街道618',
                'product_id' => $product['id'],
                'product_title' => $product['title'],
                'num' => $num,
                'price' => $price,
                'actual_price' => $price,
                'pay_type' => $payType,
                'status' => $status,
                'confirm_time' => $payTime,
                'pay_time' => $payTime,
                'createtime' => $createTime,
                'updatetime' => $createTime,
            ];

            if ($i != 500000 && $i % 5000 == 0) {
                Db::table('order')->insertAll($data);
                $data = [];
            }
        }

        //剩余部分
        if (!empty($data) && !empty($dataSnapshot)) {
            Db::table('order')->insertAll($data);
        }

        //库存扣除
        foreach ($products as $k => $v) {
            Db::table('product')->where('id', $v['id'])->update([
                'stock' => $v['stock'],
            ]);
        }

        echo "生成完了";
    }

    //随机生成产品
    private function _randProduct(&$productArr, $productIds, $productIdCount, $num)
    {
        //随机生成产品
        $productIdRand = rand(0, $productIdCount);

        //库存判断
        if ($productArr[$productIds[$productIdRand]]['stock'] >= $num) {
            //数量扣除
            $productArr[$productIds[$productIdRand]]['stock'] -= $num;
        } else {
            //兜底
            $this->_randProduct($productArr, $productIds, $productIdCount, $num);
        }
        return $productArr[$productIds[$productIdRand]];
    }

    //随机生成用户
    private function _randMember(&$memberArr, $memberCount)
    {
        //随机生成用户
        $memberId = rand(1, $memberCount);

        //没有用户信息
        if (!empty($memberArr[$memberId])) {
            return $memberArr[$memberId];
        } else {
            //查询用户信息
            $member = Db::table('member')->field('id,nickname,mobile')->where('id', $memberId)->find();
            if (empty($member)) {//兜底
                $this->_randMember($memberArr, $memberCount);
            }

            $memberArr[$memberId] = $member;
            return $member;
        }
    }

    public function order()
    {
        $firstOrder = Db::table('order')
            ->field('createtime')
            ->order('createtime', 'asc')
            ->find();

        $startDay = date('Y-m-d', $firstOrder['createtime']);

        $diffDay = floor((time() - $firstOrder['createtime']) / 86400);

        //循环日期
        for ($d = 0; $d < $diffDay; $d++) {
            if ($d > 0) {
                $day = strtotime('+' . $d . ' day', strtotime($startDay));
                $day = date('Y-m-d', $day);
            } else {
                $day = $startDay;
            }

            //循环时间
            for ($i = 0; $i <= 23; $i++) {
                $hourStart = str_pad($i, 2, '0', STR_PAD_LEFT);
                $hourEnd = str_pad($i + 1, 2, '0', STR_PAD_LEFT);
                $start = $day . " " . $hourStart . ":00:00";
                $end = $day . " " . $hourEnd . ":00:00";

                $orders = Db::table('order')
                    ->field('actual_price')
                    ->where('createtime', '>=', strtotime($start))
                    ->where('createtime', '<', strtotime($end))
                    ->select();

                (new \app\admin\model\statistics_model\Order())
                    ->table('order')
                    ->insert([
                        'date' => $day,
                        'start' => $hourStart,
                        'end' => $hourEnd,
                        'num' => count($orders),
                        'money' => array_sum(array_column($orders, 'actual_price')),
                        'createtime' => time(),
                        'updatetime' => time(),
                    ]);
            }
        }
    }
}